import React, { useCallback, useEffect } from "react";
import useMatchRoute from "./useMatchRoute";
import { useRouter } from "next/router";

export default function useMenuData() {
  const _router: any = useRouter();
  const router: any = useMatchRoute();
  const [tabData, setTabData] = React.useState<any[]>([]);
  const [activeKey, setActiveKey] = React.useState("");

  const closeTab = useCallback(
    (pathname: string = activeKey) => {
      const index = tabData.findIndex((o) => o.pathname === pathname);
      if (tabData[index].pathname === activeKey) {
        if (index > 0) {
          _router.push(tabData[index - 1].pathname);
        } else {
          _router.push(tabData[index + 1].pathname);
        }
      }
      tabData.splice(index, 1);

      setTabData([...tabData]);
    },
    [_router, activeKey, tabData]
  );

  const refreshTab = useCallback(
    (pathname: string = activeKey) => {
      setTabData((prev) => {
        const index = prev.findIndex((tab) => tab.pathname === pathname);

        if (index >= 0) {
          // 这个是react的特性，key变了，组件会卸载重新渲染
          prev[index].key = Math.random();
        }

        return [...prev];
      });
    },
    [activeKey]
  );

  const closeOtherTab = useCallback(
    (pathname: string = activeKey) => {
      setTabData((prev) => prev.filter((o) => o.pathname === pathname));
    },
    [activeKey]
  );

  useEffect(() => {
    if (!router) return;
    const existTab = tabData.find((x) => x.pathname === router.pathname);
    if (!existTab) {
      setTabData((pre) => {
        return [
          ...pre,
          {
            key: "" + Math.random(),
            label: router.label,
            pathname: router.pathname,
            children: router.children,
            icon: router.icon,
          },
        ];
      });
    }
    setActiveKey(router.pathname);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [router]);

  return { activeKey, tabData, closeTab, refreshTab, closeOtherTab };
}
